package com.wyx.filter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wyx.mapper.StoreMapper;
import com.wyx.pojo.Store;
import com.wyx.pojo.User;
import com.wyx.utils.threadSave.StoreInfoHolder;
import com.wyx.utils.threadSave.ThreadHold;
import com.wyx.utils.threadSave.ThreadUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//接口业务均在api下
@WebFilter(filterName = "loginFilter", urlPatterns = {"/**", "/smoke/*"})
//将这个对象注入为bean  或者在spring的启动类上加@ServletComponentScan  注解
@Component
@Slf4j
public class LoginFilter implements Filter {
    @Autowired
    private StoreMapper storeMapper;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        log.info("拦截到：{} 地址请求", requestURI);

        String token = request.getHeader("Authorization");
        if (token == null) {
//            TODO:
        }
        String id = decrypt(token);
        id = "4081c4a9bb81425eb7ce63dcd69b6019";
//        拿到token后，自行处理，这里假设从token获取到了id
//        对用户信息进行解密，拿到解密之后的数据，查询数据库，校验用户身份。存储到ThreadLocal下

//        根据解析之后的数据进行数据库查询，如果查询的到，将信息保存。再存一个用户信息或者什么信息，
        LambdaQueryWrapper<Store> storeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        storeLambdaQueryWrapper.eq(Store::getId, id);
        storeLambdaQueryWrapper.select(Store::getId, Store::getStoreName, Store::getSmokeCertificateId);
        Store store = storeMapper.selectOne(storeLambdaQueryWrapper);
        if (store == null) {
            return;
        }

        ThreadHold.init();
        StoreInfoHolder.save(store);
        User user = new User();
        user.setId("111");
        ThreadUserInfo.set(user);
        filterChain.doFilter(request, response);
        StoreInfoHolder.remove();
        ThreadHold.remove();
        ThreadUserInfo.remove();
    }

    //    这儿的逻辑  对当前用户的id 进行一个加密  然后在这儿再进行解密  好！！逻辑就这样
    private String decrypt(String token) {
        return "1234";
    }
}
